// src/user/user.service.ts
import { HttpException, HttpStatus, Injectable, Post, UnauthorizedException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './user.entity';
import { JwtService } from '@nestjs/jwt';
import { WechatRegisterDto } from './dto/wechat-register.dto';
import { PhoneRegisterDto } from './dto/phone-register.dto';
import { LoginDto } from './dto/login.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import * as bcrypt from 'bcryptjs';
import { RemoveDto } from './dto/remove.dto';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User)
    private userRepository: Repository<User>,
    private jwtService: JwtService,
  ) { }

  async wechatRegister(dto: WechatRegisterDto): Promise<
    { isRegister: boolean; message: string; code: number, token?: string | null, isAuthorized: boolean, isRemover: boolean }
  > {

    const existingUser = await this.userRepository.findOne({
      where: { wechatId: dto.wechatId },
    });

    if (existingUser) {
      if (existingUser.status === "0") {
        return {
          isRegister: false,
          token: null,
          isAuthorized: false,
          isRemover: true,
          message: '用户已经存在且注销, 请问是否恢复?继续注册, 失去恢复的可能性!',
          code: 400,
        };
      }
      if (existingUser.status === "1") {
        return {
          isRegister: false,
          token: null,
          isAuthorized: false,
          isRemover: true,
          message: '用户已经存在!请直接登录',
          code: 400,
        };
      } else {
        return {
          isRegister: false,
          token: null,
          isAuthorized: false,
          isRemover: false,
          message: '当前微信账号处于不正常状态, 请联系管理员!',
          code: 400,
        };
      }

    }

    const newUser = new User();
    newUser.wechatId = dto.wechatId;
    newUser.nickName = dto.nickName;
    newUser.avatar = dto.avatar || '';
    newUser.note = dto.note || '';
    newUser.userId = Math.random().toString(36).slice(2, 9); // 随机生成userId
    const plainPassword = Math.random().toString(36).slice(2, 12); // 随机生成一个密码
    const hashedPassword = await bcrypt.hash(plainPassword, 10); // 对密码进行哈希处理
    newUser.password = hashedPassword; // 存储哈希后的密码
    newUser.platform = "wechat-mp";
    newUser.status = "1";

    await this.userRepository.save(newUser);

    const payload = { userId: newUser.id, nickName: newUser.nickName };
    const token = this.jwtService.sign(payload, { expiresIn: '7d' });

    return {
      isRegister: true,
      token,
      isRemover: false,
      isAuthorized: true,
      message: '注册成功!',
      code: 200,
    };
  }

  async phoneRegister(dto: PhoneRegisterDto): Promise<
    { isRegister: boolean; message: string; code: number, token?: string | null, isAuthorized: boolean, isRemover: boolean }
  > {
    const existingUser = await this.userRepository.findOne({
      where: [{ phone: dto.phone }],
    });

    if (existingUser) {
      if (existingUser.status === "0") {
        return {
          isRegister: false,
          token: null,
          isAuthorized: false,
          isRemover: true,
          message: '用户已经存在且注销, 请问是否恢复?继续注册, 失去恢复的可能性!',
          code: 400,
        };
      }
      if (existingUser.status === "1") {
        return {
          isRegister: false,
          token: null,
          isAuthorized: false,
          isRemover: true,
          message: '用户已经存在!请直接登录',
          code: 400,
        };
      } else {
        return {
          isRegister: false,
          token: null,
          isAuthorized: false,
          isRemover: false,
          message: '当前注册的手机号码处于不正常状态, 请联系管理员!',
          code: 400,
        };
      }

    }

    const newUser = new User();
    newUser.phone = dto.phone;
    newUser.userId = dto.phone; // 假设userId与phone一致
    const plainPassword = dto.password;
    const hashedPassword = await bcrypt.hash(plainPassword, 10); // 对密码进行哈希处理
    newUser.password = hashedPassword; // 存储哈希后的密码
    newUser.nickName = dto.nickName;
    newUser.avatar = dto.avatar || '';
    newUser.note = dto.note || '';
    newUser.platform = dto.platform;
    newUser.status = "1";

    await this.userRepository.save(newUser);

    const payload = { userId: newUser.id, nickName: newUser.nickName };
    const token = this.jwtService.sign(payload, { expiresIn: '7d' });

    return {
      isRegister: true,
      token,
      isRemover: false,
      isAuthorized: true,
      message: '注册成功!',
      code: 200,
    };
  }

  async login(loginDto: LoginDto): Promise<{ isAuthorized: boolean; message: string; code: number, token: string | null, isRegister: boolean }> {
    const { userId, phone, wechatId, password } = loginDto;
    let user;
    // 微信登录
    if (wechatId) {
      user = await this.userRepository.findOne({ where: { wechatId, status: "1" } });
    }
    else if (userId || phone) {
      if (userId) {
        user = await this.userRepository.findOne({
          where: { userId, status: "1" }
        });
      }
      else {
        user = await this.userRepository.findOne({
          where: { phone, status: "1" }
        });
      }
      if (!user || !(await bcrypt.compare((password || ""), user.password))) {
        return {
          isAuthorized: false,
          token: null,
          isRegister: true,
          message: '账号或密码错误!',
          code: 400,
        };
      }
    }
    else {
      return {
        isAuthorized: false,
        token: null,
        isRegister: true,
        message: '无效的登录信息!',
        code: 400,
      };
    }

    if (!user) {
      return {
        isAuthorized: false,
        token: null,
        isRegister: false,
        message: '用户不存在, 请先注册!',
        code: 404,
      };
    }

    const payload = { userId: user.id, nickName: user.nickName };
    const token = this.jwtService.sign(payload, { expiresIn: '7d' });

    return {
      isRegister: true,
      isAuthorized: true,
      token,
      message: '登录成功!',
      code: 200,
    };
  }

  async updateUserById(updateUserDto: UpdateUserDto): Promise<{ isUpdated: boolean; message: string; code: number }> {
    const { userId, nickName, avatar, note } = updateUserDto;

    // 查找用户
    const user = await this.userRepository.findOne({ where: { userId, status: "1" } });
    if (!user) {
      throw new HttpException('用户不存在!', HttpStatus.BAD_REQUEST);
    }

    // 更新指定字段
    if (nickName) user.nickName = nickName;
    if (avatar) user.avatar = avatar;
    if (note) user.note = note;

    // 保存更改
    await this.userRepository.save(user);

    return {
      isUpdated: true,
      message: '信息更新成功!',
      code: 200,
    };
  }

  async remove(removeDto: RemoveDto): Promise<{ isRemoved: boolean; message: string; code: number }> {
    const { userId, forceRemove } = removeDto;

    // 查找用户
    const user = await this.userRepository.findOne({ where: { userId } });
    if (!user) {
      throw new HttpException('用户不存在!', HttpStatus.BAD_REQUEST);
    }

    // 注册时检测有=0,放弃之前所有信息的;
    if (forceRemove) {
      user.status = "2";
      user.note = `userId:${user.userId}||wechatId:${user.wechatId}||phone:${user.phone}`;
      user.userId = String(user.id) + "/remove:" + (new Date().toLocaleString());//这个字段是唯一的
      user.wechatId = "/";
      user.phone = "/";
    } else {
      user.status = "0";
    }
    // 保存更改
    await this.userRepository.save(user);

    return {
      isRemoved: true,
      message: '注销成功!',
      code: 200,
    };
  }
}